<template>
  <zm-view ref="view">
    <!-- 顶部 -->
    <view class="flex flex-col px-24 pt-24 bg-white" :class="{ 'pb-24': lineType !== '1,2' }">
      <view class="flex items-center">
        <view class="flex items-center mr-24" @click="cityPopup = !cityPopup">
          <text class="font-30">{{ curCityName || cityName || "定位中..." }}</text>
          <u-icon name="arrow-down-fill" size="18rpx"></u-icon>
        </view>
        <u-search
          v-model="searchCinema"
          placeholder="输入影院名称或者地址进行搜索"
          :show-action="false"
          height="62rpx"
          :input-style="{ 'font-size': '24rpx' }"
          @blur="onSearchCinemaChange"
          @clear="onSearchCinemaChange"
          @search="onSearchCinemaChange"
        ></u-search>
      </view>
      <zm-tabs v-if="lineType.length > 1" v-model="currentLineType" :list="tabs" line-width="50rpx" @change="onTabsChange"></zm-tabs>
    </view>

    <!-- 列表 -->
    <zm-list ref="list" :options="options" @query="handleQuery">
      <view class="flex flex-col py-20">
        <view v-for="(item, index) in filterCinemas" :key="index" class="flex flex-col radius-10 mx-24 mb-20">
          <view class="fex flex-col bg-white radius-10 overflow-hidden" @click="handleCinema(item)">
            <view class="py-24 flex flex-col px-24">
              <zm-text-highlight ref="nameText" font-size="30rpx" font-weight="bold" :text="item.cinemaName" :match="searchCinema"></zm-text-highlight>
              <zm-text-highlight ref="addressText" color="#999999" custom-class="mt-10" :text="item.address" :match="searchCinema"></zm-text-highlight>
            </view>
            <view v-if="type == 'coupon'" class="solid-top-2 py-24 flex flex-col px-24" @click="onClickCollapse(index)">
              <view class="flex items-center justify-between">
                <text class="text-999">详细信息</text>
                <view class="flex transition" :class="{ 'transform-rotate-180': item.active }">
                  <u-icon name="arrow-down" color="#cccccc" size="36rpx"></u-icon>
                </view>
              </view>
            </view>
          </view>
          <view class="tips-content" :class="{ 'is-active': item.active }">
            <text class="p-24 flex">{{ item.couponTip }}</text>
          </view>
        </view>
      </view>
    </zm-list>

    <!-- 城市切换 -->
    <zm-popup :show.sync="cityPopup" max-height="100vh" mode="right" width="100vw">
      <view class="p-24">
        <u-search
          v-model="searchCity"
          height="62rpx"
          action-text="取消"
          placeholder="输入城市名称和拼音"
          :input-style="{ 'font-size': '24rpx' }"
          @change="onSearchCityChange"
          @custom="cityPopup = false"
        ></u-search>
      </view>
      <u-index-list v-if="cityPopup" :index-list="cityIndexs" index-font-size="20rpx" inactive-color="#999999">
        <u-index-item v-for="(group, index) in cityGroups" :key="index">
          <u-index-anchor :text="group.initials" bg-color="#f4f6f7" size="22rpx"></u-index-anchor>
          <view v-for="(city, cityIndex) in group.list" :key="cityIndex" class="city-cell" hover-class="opacity-6" @click="onClickCityCell(city)">
            {{ city.regionName }}
          </view>
        </u-index-item>
      </u-index-list>
    </zm-popup>
  </zm-view>
</template>

<script>
import page from "@/mixins/page"
import hook from "@/mixins/hook"
import { mapGetters } from "vuex"

export default {
  mixins: [page, hook],
  data() {
    return {
      tabs: [
        { text: "线上可用影院", value: "1" },
        { text: "线下可用影院", value: "2" }
      ],
      options: { auto: false },
      lineType: [],
      saleOrderNo: "",
      currentLineType: "",
      searchCity: "",
      searchCinema: "",
      cityId: "",
      curCityName: "",
      citys: [],
      cityGroups: [],
      cityIndexs: [],
      cinemas: [],
      filterCinemas: [],
      cityPopup: false,
      type: "coupon"
    }
  },
  computed: {
    ...mapGetters(["cityName", "cityCode"])
  },
  onLoad(options) {
    if (options.type == "coupon") {
      this.lineType = options.lineType.split(",")
      this.currentLineType = this.lineType[0]
    }
    this.type = options.type
    this.saleOrderNo = options.saleOrderNo
  },
  onShow() {
    this.handleRefresh()
  },
  methods: {
    async handleRefresh() {
      await this.$nextTick()
      this.handleGetCityByCoupon()
      this.$refs.list.refresh()
    },
    async handleGetCityByCoupon() {
      const res = await uni.$api[this.type][this.type == "coupon" ? "getCityByCoupon" : "getCityByCard"]({ saleOrderNo: this.saleOrderNo })
      // const res = await uni.$api.coupon.getCityByCoupon({ saleOrderNo: this.saleOrderNo })
      this.citys = res
      this.genCityGroup()
    },
    genCityGroup() {
      if (this.searchCity) {
        // 如果输入了搜索城市，则过滤出符合条件的城市
        const filterCitys = this.citys.filter((city) => Object.values(city).some((item) => String(item)?.includes(this.searchCity)))
        // 将城市索引转换为数组，并去除重复项，并按照字母顺序排序
        this.cityIndexs = [...new Set(filterCitys.map((item) => item.initials))].sort()
        // 将城市索引转换为数组，并去除重复项，并按照字母顺序排序
        this.cityGroups = this.cityIndexs.map((initials) => {
          return { initials, list: filterCitys.filter((city) => city.initials === initials) }
        })
      } else {
        // 将城市索引转换为数组，并去除重复项，并按照字母顺序排序
        this.cityIndexs = [...new Set(this.citys.map((item) => item.initials))].sort()
        // 将城市索引转换为数组，并去除重复项，并按照字母顺序排序
        this.cityGroups = this.cityIndexs.map((initials) => {
          return { initials, list: this.citys.filter((city) => city.initials === initials) }
        })
      }
    },
    async handleQuery({ fail, success }) {
      try {
        const params = { lineType: this.currentLineType, saleOrderNo: this.saleOrderNo }
        if (this.cityId) params.cityId = this.cityId
        // const res = await uni.$api.coupon.getCinemaByCoupon(params)
        const res = await uni.$api[this.type][this.type == "coupon" ? "getCinemaByCoupon" : "getCinemaByCard"](params)
        this.cinemas = res.map((item) => {
          item.active = false
          return item
        })
        this.filterCinemas = this.cinemas
        this.onSearchCinemaChange()
        success({ list: this.filterCinemas, total: this.filterCinemas.length })
      } catch (e) {
        fail()
      }
    },
    onTabsChange() {
      this.filterCinemas = []
      this.$refs.list.refresh()
    },
    onClickCollapse(index) {
      this.cinemas[index].active = !this.cinemas[index].active
      this.$forceUpdate()
    },
    onSearchCinemaChange() {
      uni.$debounce(() => {
        this.filterCinemas = this.cinemas.filter((item) => {
          return item.cinemaName?.includes(this.searchCinema) || item.address?.includes(this.searchCinema)
        })
        if (this.filterCinemas?.length) {
          this.$nextTick(() => {
            this.$refs?.nameText.forEach((item) => item.update())
            this.$refs?.addressText.forEach((item) => item.update())
          })
        }
      }, 500)
    },
    onClickCityCell(city) {
      this.cityPopup = false
      this.cityId = city.cityId
      this.curCityName = city.regionName
      this.$refs.list.refresh()
    },
    onSearchCityChange() {
      uni.$debounce(() => {
        this.genCityGroup()
      })
    },
    handleCinema(item) {
      this.toView({
        url: "pages/cinema/cinema-schedule/cinema-schedule",
        params: {
          cinemaId: item.cinemaId
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tips-content {
  height: 0;
  color: #999999;
  overflow: hidden;
  transition: all 0.3s ease;
  border-radius: 0 0 10rpx 10rpx;
  background: linear-gradient(180deg, #f5f5f5 0%, #ffffff 100%);
  &.is-active {
    height: auto;
  }
}
.city-cell {
  font-size: 26rpx;
  padding: 14rpx 24rpx;
  position: relative;
  background-color: #fff;
  &::after {
    content: "";
    left: 24rpx;
    right: 24rpx;
    bottom: 0;
    position: absolute;
    border-bottom: 2rpx solid #f4f6f7;
  }
}
</style>
